package com.itheima.reggie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service

public class OrderServiceImpl extends
        ServiceImpl<OrderMapper, Orders> implements
        OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private OrderService orderService;

    /**
     * 用户下单
     * @param orders
     */
    @Transactional
    public void submit(Orders orders) {
        //获得当前用户id
        Long userId = BaseContext.getCurrentId();

        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);

        if(shoppingCarts == null || shoppingCarts.size() == 0){
            throw new CustomException("购物车为空，不能下单");
        }

        //查询用户数据
        User user = userService.getById(userId);

        //查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if(addressBook == null){
            throw new CustomException("用户地址信息有误，不能下单");
        }

        long orderId = IdWorker.getId();//订单号

        AtomicInteger amount = new AtomicInteger(0);

        //组装订单明细信息
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //组装订单数据
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        //orders.setUserName(addressBook.getConsignee());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //向订单表插入数据，一条数据
        this.save(orders);

        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetails);

        //清空购物车数据
        shoppingCartService.remove(wrapper);
    }

    @Transactional
    public Page<OrdersDto> PageQuery(Integer page, Integer pageSize, String number, String beginTime, String endTime){
        //参数封装
        Page<Orders> pageInfo = new Page(page, pageSize);
        Page<OrdersDto> pageDto = new Page();
        //封装查询条件
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();

        qw.orderByAsc(Orders::getOrderTime);
        qw.like(StringUtils.isNotEmpty(number),Orders::getNumber,number);
        //对订单创建时间进行范围查询
        qw.gt(StringUtils.isNotEmpty(beginTime),Orders::getOrderTime,beginTime);
        qw.lt(StringUtils.isNotEmpty(endTime),Orders::getOrderTime,endTime);

        orderService.page(pageInfo,qw);

        BeanUtils.copyProperties(pageInfo,pageDto,"records");
        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> list = records.stream().map((item)->{
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item,ordersDto);
            //查询订单明细表并注入到orderDto中
            LambdaQueryWrapper<OrderDetail> orderDetails = new LambdaQueryWrapper<>();
            orderDetails.eq(OrderDetail::getOrderId,item.getId());
            List<OrderDetail> details = orderDetailService.list(orderDetails);
            ordersDto.setOrderDetails(details);
            /*//根据用户id获取到用户名字
            User user = userService.getById(item.getUserId());
            ordersDto.setUserName(user.getName());*/
            //根据地址id获取地址
            AddressBook addressBook = addressBookService.getById(item.getAddressBookId());
            ordersDto.setAddress(addressBook.getDetail());
            ordersDto.setConsignee(addressBook.getConsignee());
            return ordersDto;

        }).collect(Collectors.toList());

        pageDto.setRecords(list);

        return pageDto;
    }

    @Transactional
    public void again(Orders orders){

        Long userId = BaseContext.getCurrentId();

        Long id = orders.getId();
        LambdaQueryWrapper<OrderDetail> orderDetail = new LambdaQueryWrapper<>();
        orderDetail.eq(OrderDetail::getOrderId,id);
        //查询购物车中所有订单明细
        List<OrderDetail> orderDetailList = orderDetailService.list(orderDetail);
        //清除购物车
        shoppingCartService.cleanall();

        List<ShoppingCart> list = orderDetailList.stream().map((item)->{

            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setName(item.getName());
            shoppingCart.setImage(item.getImage());
            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();
            if(dishId!=null){
                shoppingCart.setDishId(dishId);
            }else {
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

       /* ArrayList<ShoppingCart> shoppingCarts = new ArrayList<>();

        for (OrderDetail detail : orderDetailList) {

            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtil.copyProperties(detail,shoppingCart);

            shoppingCart.setUserId(userId);
            shoppingCarts.add(shoppingCart);
        }*/
        //shoppingCartService.saveBatch(orderDetailList);
        shoppingCartService.saveBatch(list);
    }


}
